﻿using leetcodeAnswer.Code;
using System;
using System.Collections.Generic;
using System.Text;

namespace leetcodeAnswer.Answer
{
    [Answer(
        Index = 2,
        Name = "两数相加",
        Url = "https://leetcode-cn.com/problems/add-two-numbers/",
        Descript = @"给出两个 非空 的链表用来表示两个非负的整数。其中，它们各自的位数是按照 逆序 的方式存储的，并且它们的每个节点只能存储 一位 数字。
如果，我们将这两个数相加起来，则会返回一个新的链表来表示它们的和。
您可以假设除了数字 0 之外，这两个数都不会以 0 开头。
示例：
输入：(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出：7 -> 0 -> 8
原因：342 + 465 = 807")]
    public class No_002_AddTwoNumbers
    {
        [AnswerRun]
        public ListNode AddTwoNumbers(ListNode l1, ListNode l2)
        {
            ListNode root = new ListNode(0);
            ListNode _current = root;
            int _carry = 0;
            while (l1 != null || l2 != null || _carry != 0)
            {
                int l1_value = l1 != null ? l1.val : 0;
                int l2_value = l2 != null ? l2.val : 0;
                int sumVal = l1_value + l2_value + _carry;
                _carry = sumVal / 10;

                ListNode sumNode = new ListNode(sumVal % 10);
                _current.next = sumNode;
                _current = sumNode;

                if (l1 != null) l1 = l1.next;
                if (l2 != null) l2 = l2.next;
            }

            return root.next;
        }

        /// <summary>
        /// 验证参数
        /// </summary>
        [AnswerParameter]
        public List<object[]> Parameter { get; set; }

        public No_002_AddTwoNumbers()
        {
            Parameter = new List<object[]>() {
                new object[]{
                    new ListNode(2) { next = new ListNode(4) { next = new ListNode(3) } },
                    new ListNode(5) { next = new ListNode(6) { next = new ListNode(4) } }
                },
                new object[]{
                    new ListNode(5) { next = new ListNode(6) { next = new ListNode(7) } },
                    new ListNode(9) { next = new ListNode(8) { next = new ListNode(7) } }
                },
            };
        }

        /**
         * Definition for singly-linked list.
         * public class ListNode {
         *     public int val;
         *     public ListNode next;
         *     public ListNode(int x) { val = x; }
         * }
         */
        public class ListNode
        {
            public int val;
            public ListNode next;
            public ListNode(int x) { val = x; }
        }
    }
}
